#! /usr/bin/python
#----PYTHON FOR SIGNATRUE TESTING TOOL----
import sqlite3
import httplib
import socket
#import telnetlib
import sys
import time
import re
EXAMPLE = 4
def usage():
	#"usage massage show"
	print("http_server.py <ListenIP> <ListenPORT> <SQLITE_DB_NAME>")


def connect_sql_db(dbname):
	print("connect sqlite db name:%s"%(dbname))
	db=sqlite3.connect(dbname)
	return db

def sql_search(db,sig):
	print("sql_search!---------------------------")
	cur = db.cursor()
	sql ="""select * from signature_rule where signature_id =\'%s\'"""%(sig)
	print(sql)
	cur.execute(sql)
	row = cur.fetchone()
	#print(row)
	if(row != None):
		try:
			msg = str(row[EXAMPLE])
		except:
			msg = row[EXAMPLE].encode('utf-8')
	else:
		msg = None
	cur.close()
	return msg

def socket_init(ip,port):
	try:
		s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	except socket.error as elog:
		s = None
		print("error occurrence:%s\n"%(str(elog[0])))
		return None
	try:
		s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
		s.bind((str(ip),int(port)))
	except socket.error as elog:
		s.close()
		print("error occurrence:%s\n"%(str(elog[0])))
		s = None
		return None
	try:
		s.listen(10)
	except socket.error as elog:
		s.close()
		print("error occurrence:%s\n"%(str(elog[0])))
		s = None
		return None
	print("Server listen %s:%d "%(str(ip),int(port)))
	return s

def search_signature_id(msg):
	s = str(msg)
	index =s.find("Sigature-id:")

	if(index < 0):
		#print("Not find signature id index!")
		sig = None
	else:
		sig = str( s[index+12:index+21])
		print("signature id from db: %s "%(str(sig)))
	return sig

def server_dispatch(db,listen):
	f = open("server_debug.txt","w")
	while(True):
		(s,addr) = listen.accept()
		s.settimeout(5)
		try:
			req_msg = s.recv(8192)
		except socket.error as elog:
			print("recv msg timeout!\n")
			req_msg = "socket timeout"
		if(req_msg.find("socket timeout") >= 0):
			s.close()
			continue
		sig = search_signature_id(req_msg)
		if(sig != None):
			rsp_msg = sql_search(db,str(sig))
			if(rsp_msg == None):
				rsp_msg = RSP_DEF
				print("Not find response message of signature id :%s "%(str(sig)))
			else:
				while(rsp_msg.find('<#')>= 0 or rsp_msg.find("#>")>= 0):
					if rsp_msg.find('<#') >=0:
						rsp_msg =rsp_msg.replace('<#','')
					if rsp_msg.find('#>') >= 0:
						rsp_msg =rsp_msg.replace('#>','')
		else:
			rsp_msg = RSP_DEF
		print("----------------\n"+rsp_msg)
		s.send(rsp_msg)
		s.close()
	f.close()



def main(ip,port,dbname):
	db = connect_sql_db(dbname)
	
	s = socket_init(ip,port)
	server_dispatch(db ,s)
	db.close()
	s.close()
	sys.exit()

if len(sys.argv) != 4:
	usage()
	sys.exit()

Listen_ip = sys.argv[1]
Port = sys.argv[2]
Sql_db = sys.argv[3]

RSP_DEF = "HTTP/1.1 200 OK \r\n\r\n"

#RSP_DEF ="HTTP/1.1 404 Not Found \r\nDate: Wed, 30 Jan 2013 09:48:44 GMT\r\nServer:Apache/2.2.17 (Unix) PHP/5.3.5\r\nLast-Modified: Sat, 20 Nov 2004 20:16:24GMT\r\nAccept-Ranges: bytes\r\nContent-Length: 44\r\nKeep-Alive: timeout=5,max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n<html><body><h1>It works!</h1></body></html>\r\n\r\n"
#RSP_DEF ="HTTP/1.1 200 OK \r\nDate: Wed, 30 Jan 2013 09:48:44 GMT\r\nServer:Apache/2.2.17 (Unix) PHP/5.3.5\r\nLast-Modified: Sat, 20 Nov 2004 20:16:24GMT\r\nAccept-Ranges: bytes\r\nContent-Length: 44\r\nKeep-Alive: timeout=5,max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n<html><body><h1>It works!</h1></body></html>\r\n\r\n"



if __name__ == "__main__":
	main(Listen_ip,Port,Sql_db)


